/*
 * Thread.cpp
 *
 *  Created on: 2011/07/02
 *      Author: naoki
 */

#include "NTEngine/NTEngine.h"
#include "NTEngine/Threading/Thread.h"
#include "NTEngine/Threading/Event.h"

#include "Threading/src/ManagerImpl.h"

namespace NTEngine {
namespace Threading {

class Thread::Impl {
public:
	Impl() {
		mFinished = Event::create();
	}

	Event mFinished;
};

Thread::Thread()
: mImpl( NULL ) {
}

void Thread::start() {
	join();
	mImpl = NEW Impl();
	gManagerImpl->add( this, &mImpl->mFinished );
}

void Thread::join() {
	if ( mImpl ) {
		mImpl->mFinished.wait();
		SAFE_DELETE( mImpl );
	}
}

bool Thread::isFinished() {
	bool ret = false;
	if ( mImpl ) {
		if ( mImpl->mFinished.isSet() ) {
			SAFE_DELETE( mImpl );
			ret = true;
		}
	} else {
		ret = true;
	}
	return ret;
}

Thread::~Thread() {
	HARD_ASSERT( ( mImpl == NULL ) && "You must call join() or isFinished() before destruction." );
}

} // namespace Threading
} // namespace NTEngine
